/*
 *
 *
Copyright (c) 1998-2001 Aristar, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. The end-user documentation included with the redistribution, if any,
must include the following acknowledgment:

"This product includes software developed by Aristar, Inc. (http://www.aristar.com/)."

Alternately, this acknowledgment may appear in the software itself, if and
wherever such third-party acknowledgments normally appear.

4. The names "Dialect" and "Aristar, Inc." must not be used to endorse or
promote products derived from this software without prior written permission.
For written permission, please contact info@aristar.com.

5. Products derived from this software may not be called "Dialect", nor may
"Dialect" appear in their name, without prior written permission of Aristar, Inc.

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
ARISTAR, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software consists of voluntary contributions made by many individuals
on behalf of Aristar, Inc.  For more information on Aristar, Inc.,
please see <http://www.aristar.com/>.

Portions of this software are based upon software freely available and
written by individuals not associated with Aristar, Inc.  Copyrights are
maintained in the relevant source code files.
 *
 *
 */

#include "stdafx.h"
#include "CommPort.h"

CCommPort::CSharedData::CSharedData()
{
	m_hPort = INVALID_HANDLE_VALUE;
	m_bufCount = 0;
	m_hReadBufMutex = NULL;
	m_hReadWriteMutex = NULL;
	m_bWriteWantsPort = false;
	m_bStopThread = NULL;
}

CCommPort::CSharedData::~CSharedData()
{
	m_bWriteWantsPort = false;	// Stops an infinite loop in thread
	if (m_bStopThread != NULL) {
		m_bStopThread = true;
	}
	if (m_hPort != INVALID_HANDLE_VALUE) {
		CloseHandle(m_hPort);
		m_hPort = INVALID_HANDLE_VALUE;
	}
}

////////////////////////////////

CCommPort::CCommPort()
{
	m_pData = NULL;
}

CCommPort::~CCommPort()
{
	// The thread will delete m_pData
	Close();
}

void CCommPort::Close()
{
	if (m_pData != NULL) {
		CloseHandle(m_pData->m_hReadWriteMutex);
		m_pData->m_hReadWriteMutex = NULL;
		CloseHandle(m_pData->m_hReadBufMutex);
		m_pData->m_bStopThread = true;
		m_pData = NULL;
	}
}

bool CCommPort::Open(CString port, DWORD baud, BYTE byteSize, BYTE parity, BYTE stopBits)
{
	if (m_pData != NULL) return false; // Already open, close first!

	ASSERT(m_pData == NULL);
	m_pData = new CSharedData();

	// Open the serial port.
	m_pData->m_hPort = CreateFile (
		port,							// Pointer to the name of the port
		GENERIC_READ | GENERIC_WRITE,	// Access (read/write) mode
		0,								// Share mode
		NULL,							// Pointer to the security attribute
		OPEN_EXISTING,					// How to open the serial port
		0,								// Port attributes
		NULL);							// Handle to port with attribute to copy

	if (m_pData->m_hPort == INVALID_HANDLE_VALUE) {
		delete m_pData;
		m_pData = NULL;
		return false;
	}

	m_pData->m_hReadBufMutex = CreateMutex(NULL, FALSE, NULL);
	m_pData->m_hReadWriteMutex = CreateMutex(NULL, FALSE, NULL);
	if ((m_pData->m_hReadBufMutex == NULL) || (m_pData->m_hReadWriteMutex == NULL)) {
		delete m_pData;
		m_pData = NULL;
		return false;
	}

	DCB PortDCB;
	PortDCB.DCBlength = sizeof(DCB);
	GetCommState (m_pData->m_hPort, &PortDCB);	// Get the default port setting information.

	// Change the DCB structure settings.
	PortDCB.BaudRate = baud;              // Current baud
	PortDCB.ByteSize = byteSize;          // Number of bits/bytes, 4-8
	PortDCB.Parity = parity;              // 0-4=no,odd,even,mark,space
	PortDCB.StopBits = stopBits;          // 0,1,2 = 1, 1.5, 2

	PortDCB.fBinary = TRUE;               // Binary mode; no EOF check
	PortDCB.fParity = TRUE;               // Enable parity checking.
	PortDCB.fOutxCtsFlow = FALSE;         // No CTS output flow control
	PortDCB.fOutxDsrFlow = FALSE;         // No DSR output flow control
	PortDCB.fDtrControl = DTR_CONTROL_ENABLE; // DTR flow control type
	PortDCB.fDsrSensitivity = FALSE;      // DSR sensitivity
	PortDCB.fTXContinueOnXoff = TRUE;     // XOFF continues Tx
	PortDCB.fOutX = FALSE;                // No XON/XOFF out flow control
	PortDCB.fInX = FALSE;                 // No XON/XOFF in flow control
	PortDCB.fErrorChar = FALSE;           // Disable error replacement.
	PortDCB.fNull = FALSE;                // Disable null stripping.
	PortDCB.fRtsControl = RTS_CONTROL_ENABLE; // RTS flow control
	PortDCB.fAbortOnError = FALSE;        // Do not abort reads/writes on error.

	// Configure the port according to the specifications of the DCB structure.
	if (!SetCommState(m_pData->m_hPort, &PortDCB)) {
		delete m_pData;
		m_pData = NULL;
		return false;
	}

	// Retrieve the time-out parameters for all read and write operations on the port.
	COMMTIMEOUTS CommTimeouts;
	GetCommTimeouts (m_pData->m_hPort, &CommTimeouts);

	// Change the COMMTIMEOUTS structure settings.
	CommTimeouts.ReadIntervalTimeout = MAXDWORD;
	CommTimeouts.ReadTotalTimeoutMultiplier = 0;
	CommTimeouts.ReadTotalTimeoutConstant = 0;
	CommTimeouts.WriteTotalTimeoutMultiplier = 10;
	CommTimeouts.WriteTotalTimeoutConstant = 1000;

	// Set the time-out parameters for all read and write operations on the port.
	if (!SetCommTimeouts(m_pData->m_hPort, &CommTimeouts)) {
		delete m_pData;
		m_pData = NULL;
		return false;
	}

	// Direct the port to perform extended functions SETDTR and SETRTS.
	// SETDTR: Sends the DTR (data-terminal-ready) signal.
	// SETRTS: Sends the RTS (request-to-send) signal.
	EscapeCommFunction (m_pData->m_hPort, SETDTR);
	EscapeCommFunction (m_pData->m_hPort, SETRTS);

	// Create a read thread for reading data from the communication port.
	DWORD dwThreadID;
	HANDLE hReadThread;
	if (hReadThread = CreateThread(NULL, 0, this->ReadThread, (LPVOID)m_pData, 0, &dwThreadID)) {
		CloseHandle(hReadThread);
	}
	else {
		delete m_pData;
		m_pData = NULL;
		return false;
	}
	return true;
}

int CCommPort::Write(CString data)
{
	if (data.IsEmpty()) return 0;

	int count = 0;
	m_pData->m_bWriteWantsPort = true;
	if (WaitForSingleObject(m_pData->m_hReadWriteMutex, 2000) == WAIT_OBJECT_0) {
		BYTE byte;
		DWORD bytesWritten;
		LPCTSTR lpData= data;
		for (int idx = 0; idx < data.GetLength(); ++idx) {
			byte = (BYTE)(lpData[idx]);
			WriteFile(m_pData->m_hPort, &byte, 1, &bytesWritten, NULL);
			if (bytesWritten == 0) break;
			count++;
		}
		ReleaseMutex(m_pData->m_hReadWriteMutex);
	}
	m_pData->m_bWriteWantsPort = false;
	return count;
}

int CCommPort::Write(const LPBYTE data, DWORD byteCount)
{
	if ((data == NULL) || (byteCount == 0)) return 0;

	int count = 0;
	m_pData->m_bWriteWantsPort = true;
	if (WaitForSingleObject(m_pData->m_hReadWriteMutex, 2000) == WAIT_OBJECT_0) {
		DWORD bytesWritten;
		for (DWORD idx = 0; idx < byteCount; ++idx) {
			WriteFile(m_pData->m_hPort, data + idx, 1, &bytesWritten, NULL);
			if (bytesWritten == 0) break;
			count++;
		}
		ReleaseMutex(m_pData->m_hReadWriteMutex);
	}
	m_pData->m_bWriteWantsPort = false;
	return count;
}

CString CCommPort::Read()
{
	CString result;
	// Lock mutex, copy bytes into buf, unlock mutex
	if (WaitForSingleObject(m_pData->m_hReadBufMutex, 200) == WAIT_OBJECT_0) {
		LPTSTR buf = result.GetBuffer(m_pData->m_bufCount);
		#ifdef UNICODE
			for (int idx = 0; idx < m_pData->m_bufCount; ++idx) {
				buf[idx] = (TCHAR)(m_pData->m_ReadBuffer[idx]);
			}
		#else
			memcpy(buf, m_pData->m_ReadBuffer, m_pData->m_bufCount);
		#endif
		result.ReleaseBuffer(m_pData->m_bufCount);
		m_pData->m_bufCount = 0;
		ReleaseMutex(m_pData->m_hReadBufMutex);
	}
	return result;
}

int CCommPort::Read(LPBYTE buf, int bufSize)
{
	int count = 0;
	if (WaitForSingleObject(m_pData->m_hReadBufMutex, 200) == WAIT_OBJECT_0) {
		if (bufSize >= m_pData->m_bufCount) {
			count = m_pData->m_bufCount;
			memcpy(buf, m_pData->m_ReadBuffer, count);
			m_pData->m_bufCount = 0;
		}
		else {
			count = bufSize;
			m_pData->m_bufCount -= count;
			memcpy(buf, m_pData->m_ReadBuffer, count);
			// Slide the remaining data to the head of the buffer
			// Probably more efficient to simply keep a head index (maybe later)
			memmove(m_pData->m_ReadBuffer, m_pData->m_ReadBuffer + count, m_pData->m_bufCount);
		}
		ReleaseMutex(m_pData->m_hReadBufMutex);
	}
	return count;
}

DWORD CCommPort::ReadThread(LPVOID lpVoid)
{
	CSharedData* pData = (CSharedData*)lpVoid;
	ASSERT(pData != NULL);
	ASSERT(pData->m_bufCount == 0);

	HANDLE hPort = pData->m_hPort;
	HANDLE hReadWriteMutex = pData->m_hReadWriteMutex;
	HANDLE hReadBufMutex = pData->m_hReadBufMutex;
	BYTE* ReadBuffer = pData->m_ReadBuffer;

	BYTE byte;
	DWORD dwBytesRead, dwErrors;
	COMSTAT cs;

	while (!pData->m_bStopThread) {
		// If our buffer is full, don't allow reading more until it is emptied
		while (pData->m_bufCount >= READ_BUF_SIZE) {
			Sleep(100);
		}
		while (pData->m_bWriteWantsPort) {
			Sleep(0); // Can't read and write at the same time
		}

		if (ClearCommError(hPort, &dwErrors, &cs) && (cs.cbInQue > 0)) {
			if (WaitForSingleObject(hReadWriteMutex, INFINITE) == WAIT_OBJECT_0) {
				// Lock mutex, append chars to buffer, unlock mutex
				if (WaitForSingleObject(hReadBufMutex, INFINITE) == WAIT_OBJECT_0) {
					for (DWORD loop = 0; !pData->m_bStopThread && (loop < cs.cbInQue) && (pData->m_bufCount < READ_BUF_SIZE); ++loop) {
						ReadFile(hPort, &byte, 1, &dwBytesRead, NULL);
						if (dwBytesRead > 0) {
							ReadBuffer[pData->m_bufCount++] = byte;
						}
					}
					ReleaseMutex(hReadBufMutex);
				}
				ReleaseMutex(hReadWriteMutex);
			}
		}
	}
	delete pData;	// Thread cleans up shared info since it dies last
	OutputDebugString(_T("*** Serial port thread is terminating...\n"));
	return 0;
}
